//
//  ZRLController.m
//  BSProject
//
//  Created by Machine on 2019/8/8.
//  Copyright © 2019 beisheng. All rights reserved.
//

#import "ZRLController.h"
#import "FDWebSocket.h"
#import "BSSocket.h"


@interface ZRLController ()
@property (nonatomic, strong) NSMTextView *tv;
@property (nonatomic, strong) UITextField *locTextField;
@property (nonatomic, strong) UITextField *lengthTextField;
@property (nonatomic) struct BSDataRecvO recvO;
@property (nonatomic, strong) UITextField *field;
@property (nonatomic, strong) UITextField *field1;
@end

@implementation ZRLController

#pragma mark - lifeCycle

#pragma mark - override
- (void)didInitialize {
    [super didInitialize];
    
    struct BSDataRecvO recv;
    memset(&recv, 0, sizeof(recv));
    self.recvO = recv;
}

#pragma mark - initialization
- (void)viewDidLoad {
    [super viewDidLoad];
    
    MyLinearLayout *layout = [MyLinearLayout linearLayoutWithOrientation:MyOrientation_Vert];
    layout.myHorzMargin = 0;
    layout.gravity = MyGravity_Horz_Center;
    layout.padding = UIEdgeInsetsMake(15, 15, 15, 15);
    layout.subviewVSpace = 15;
    [self.view addSubview:layout];
    
    {
        MyLinearLayout *sub = [MyLinearLayout linearLayoutWithOrientation:MyOrientation_Horz];
        sub.myHorzMargin = 0;
        sub.wrapContentHeight = YES;
        sub.subviewHSpace = 15;
        sub.gravity = MyGravity_Vert_Center;
        [layout addSubview:sub];
        
        {
            NSMButton *btn = NSMButton.new;
            btn.weight = 1;
            btn.height = 44;
            btn.backgroundColor = RandomColor();
            btn.titleLabel.font = CustomFont(14);
            [btn setTitleColor:COLOR_4 forState:UIControlStateNormal];
            btn.title = @"连接";
            [sub addSubview:btn];
            [btn addTarget:self action:@selector(socketConnent) forControlEvents:UIControlEventTouchUpInside];
        }
        {
            NSMButton *btn = NSMButton.new;
            btn.weight = 1;
            btn.height = 44;
            btn.backgroundColor = RandomColor();
            btn.titleLabel.font = CustomFont(14);
            [btn setTitleColor:COLOR_4 forState:UIControlStateNormal];
            btn.title = @"断开";
            [sub addSubview:btn];
            [btn addBlockForControlEvents:UIControlEventTouchUpInside block:^(id  _Nonnull sender) {
                [self wCmd:YES];
            }];
        }
    }
    
    {
        MyLinearLayout *sub = [MyLinearLayout linearLayoutWithOrientation:MyOrientation_Horz];
        sub.myHorzMargin = 0;
        sub.wrapContentHeight = YES;
        sub.subviewHSpace = 20;
        sub.gravity = MyGravity_Vert_Center;
        [layout addSubview:sub];
        
        UITextField *field = UITextField.new;
        field.weight = 1;
        field.height = 36;
        field.backgroundColor = UIColor.yellowColor;
        field.textColor = COLOR_0;
        field.clearButtonMode = UITextFieldViewModeWhileEditing;
        field.text = @"192.168.1.99";
        [sub addSubview:field];
        _field = field;
        
        UITextField *field1 = UITextField.new;
        field1.weight = 1;
        field1.height = 36;
        field1.backgroundColor = UIColor.yellowColor;
        field1.textColor = COLOR_0;
        field1.clearButtonMode = UITextFieldViewModeWhileEditing;
        field1.text = @"5000";
        [sub addSubview:field1];
        _field1 = field1;
        
        NSMButton *btn = NSMButton.new;
        btn.size = CGSizeMake(100, 44);
        btn.backgroundColor = RandomColor();
        btn.titleLabel.font = CustomFont(14);
        [btn setTitleColor:COLOR_4 forState:UIControlStateNormal];
        btn.title = @"发送";
        [sub addSubview:btn];
        
        
        /*
         htonl、htons本机序到网络序
         ntohl、ntohs网络序到本机序
         */
        [btn addBlockForControlEvents:UIControlEventTouchUpInside block:^(id  _Nonnull sender) {
             [_bsSocket send:field.text];
        }];
    }
    
    {
        
        MyFlowLayout *fLayout = [MyFlowLayout flowLayoutWithOrientation:MyOrientation_Vert arrangedCount:4];
        fLayout.myHorzMargin = 0;
        fLayout.wrapContentHeight = YES;
        fLayout.subviewSpace = 15;
        [layout addSubview:fLayout];
        
        NSArray *array = @[@"手动",@"原点复位",@"步进",@"自动",@"手动速度+",@"手动速度-", @"自动速度+",@"自动速度-", @"自动开始", @"自动暂停"].mutableCopy;
        for (int index  = 0; index < array.count; index ++) {
            NSMButton *btn = NSMButton.new;
            btn.weight = 1;
            btn.height = 44;
            btn.backgroundColor = RandomColor();
            btn.titleLabel.font = CustomFont(14);
            [btn setTitleColor:COLOR_4 forState:UIControlStateNormal];
            btn.title = SafeString(array[index]);
            btn.tag = index;
            [fLayout addSubview:btn];
            [btn addTarget:self action:@selector(actionButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        NSMButton *btn = NSMButton.new;
        btn.size = CGSizeMake(100, 44);
        btn.backgroundColor = RandomColor();
        btn.titleLabel.font = CustomFont(14);
        [btn setTitleColor:COLOR_4 forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(sendW) forControlEvents:UIControlEventTouchUpInside];
        btn.title = @"发送W";
        [fLayout addSubview:btn];
    }
    
    {
        MyLinearLayout *sub = [MyLinearLayout linearLayoutWithOrientation:MyOrientation_Horz];
        sub.myHorzMargin = 0;
        sub.wrapContentHeight = YES;
        sub.subviewHSpace = 20;
        sub.gravity = MyGravity_Vert_Center;
        [layout addSubview:sub];
        
        
        UITextField *field = UITextField.new;
        field.weight = 1;
        field.height = 36;
        field.backgroundColor = UIColor.yellowColor;
        field.textColor = COLOR_0;
        field.clearButtonMode = UITextFieldViewModeWhileEditing;
        field.text = @"2V";
        [sub addSubview:field];
        
        NSMButton *btn = NSMButton.new;
        btn.size = CGSizeMake(100, 44);
        btn.backgroundColor = RandomColor();
        btn.titleLabel.font = CustomFont(14);
        [btn setTitleColor:COLOR_4 forState:UIControlStateNormal];
        btn.title = @"发送";
        [sub addSubview:btn];
        
        [btn addBlockForControlEvents:UIControlEventTouchUpInside block:^(id  _Nonnull sender) {
            [_bsSocket send:field.text];
        }];
        
        sub.myVisibility = MyVisibility_Gone;
    }
    
    NSMTextView *textView = NSMTextView.new;
    textView.backgroundColor = UIColor.redColor;
    textView.size = CGSizeMake(kScreenWidth - 40, kScreenHeight *0.4);
    textView.textColor = COLOR_0;
    [layout addSubview:textView];
    _tv = textView;
}


#pragma mark - setter/getter

#pragma mark - network

#pragma mark - method/public

#pragma mark - method/private
- (void)showText:(id)text {
    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"%@", text);
        self.tv.text = FormatString(@"%@\n%@", self.tv.text, text);
        [self.tv scrollToBottom];
    });
}

#pragma mark - action
- (void)socketConnent {
    [self showText:@"准备连接..."];
    NSString *ipstr = self.field.text;
    int port = [self.field1.text integerValue];
    [_bsSocket connectHost:ipstr onPort:port];
    
    @nsm_weak(self)
    _bsSocket.didConnectSuccess = ^{
        @nsm_strong(self)
        [self showText:@"连接成功"];
        
        //[_bsSocket send:@"2O"];
    };
    _bsSocket.didConnectFailure = ^(NSError * _Nonnull error) {
        @nsm_strong(self)
        [self showText:FormatString(@"连接失败:%@", error.localizedDescription)];
    };
    _bsSocket.didDisconnect = ^(NSError * _Nonnull error) {
        @nsm_strong(self)
        [self showText:FormatString(@"连接关闭:%@", error.localizedDescription)];
    };
    
    _bsSocket.didSendData = ^(NSData*  _Nonnull data) {
        @nsm_strong(self)
        [self showText:FormatString(@"发送数据:%@ length : %@", data,@(data.length))];
    };
    _bsSocket.didReceiveData = ^(NSData  *_Nonnull data) {
#pragma mark - 收到数据
        NSData *subData = [data subdataWithRange:NSMakeRange(0, 3)];
        struct BSHeaderRecv recv;
        [subData getBytes:&recv length:sizeof(recv)];
        NSString *cmd = FormatString(@"%c", recv.cmd);

        @nsm_strong(self)
        [self showText:FormatString(@"收到原始数据[%@] length:%@\n%@", cmd, @(data.length), data)];
        
        [self showText:FormatString(@"解析原始数据[%@]", cmd)];
        if (recv.cmd == 'V')
            [self receiveVData:data];
        else if (recv.cmd == 'R')
            [self receiveRData:data];
        else if (recv.cmd == 'O') {
            [self receiveOData:data];
        }
    };
    _bsSocket.didReconnecting = ^(NSUInteger count) {
        @nsm_strong(self)
        [self showText:FormatString(@"第%@次重连...", @(count))];
    };
}

- (void)receiveVData:(NSData *)data{
    struct BSVersion version;
    memset(&version, 0, sizeof(version));
    [data getBytes:&version length:sizeof(version)];
    
    NSMutableArray *strs = @[].mutableCopy;
    [strs addObject:FormatString(@"Main 系统 = %@", DataToString(version.sysVer))];
    [strs addObject:FormatString(@"Main 系统 = %@", DataToString(version.sysVer))];
    [strs addObject:FormatString(@"Table程序 = %@", DataToString(version.seqVer))];
    [strs addObject:FormatString(@"初始化数据 = %@", DataToString(version.initVer))];
    [strs addObject:FormatString(@"Motion系统 = %@", DataToString(version.motVer))];
    [strs addObject:FormatString(@"轴参数 = %@", DataToString(version.spcVer))];

    // Axis servo svcVer[8][8]
    for (int i=0; i<8; i++) {
        NSString *axis = FormatString(@"Axis%d Servo",i+1);
        [strs addObject:FormatString(@"%@ = %@", axis, DataToString(version.svcVer[i]))];
    }
    
    [self showText:FormatString(@"版本信息显示:\n%@",[strs componentsJoinedByString:@"\n"])];
}

- (void)receiveRData:(NSData *)data{
    struct BSMachineInfo info;
    memset(&info, 0, sizeof(info));
    [data getBytes:&info length:sizeof(info)];

    NSString *ipStr = @"";
    NSString *subMaskStr = @"";
    NSString *gatwayStr = @"";
    NSString *dnsStr = @"";
    for (int i=0; i<4; i++) {
        NSString *a = [NSString stringWithFormat:@"%d",info.IP[i]];
        ipStr = [ipStr stringByAppendingString:FormatString(@"%@.",a)];

        NSString *b = [NSString stringWithFormat:@"%d",info.SubMask[i]];
        subMaskStr = [subMaskStr stringByAppendingString:FormatString(@"%@.",b)];
        
        NSString *c = [NSString stringWithFormat:@"%d",info.Default_Getway[i]];
        gatwayStr = [gatwayStr stringByAppendingString:FormatString(@"%@.",c)];
        
        NSString *d = [NSString stringWithFormat:@"%d",info.DNS[i]];
        dnsStr = [dnsStr stringByAppendingString:FormatString(@"%@.",d)];
    }
    
    NSMutableArray *strs = @[].mutableCopy;
    [strs addObject:FormatString(@"机器编号 = %@", DataToString(info.MachineNo))];
    [strs addObject:FormatString(@"IP地址 = %@", ipStr)];
    [strs addObject:FormatString(@"子网掩码 = %@", subMaskStr)];
    [strs addObject:FormatString(@"默认网关 = %@", gatwayStr)];
    [strs addObject:FormatString(@"DNS服务器 = %@", dnsStr)];

    [self showText:FormatString(@"取出机信息数据:\n%@",[strs componentsJoinedByString:@"\n"])];
}

- (void)receiveOData:(NSData *)data{
    struct BSDataRecvO onTime;
    memset(&onTime, 0, sizeof(onTime));
    [data getBytes:&onTime length:sizeof(onTime)];
    
    self.recvO = onTime;
    
    NSMutableArray *strs = @[].mutableCopy;
    [strs addObject:FormatString(@"取出机状态SMO = %@", @"")];
    [strs addObject:FormatString(@"成型周期 = %d", onTime.done)];
    [strs addObject:FormatString(@"取出周期 = %d", onTime.take)];
    [strs addObject:FormatString(@"全周期 = %d", onTime.all)];
    [strs addObject:FormatString(@"取出数 = %d", onTime.num)];
    [strs addObject:FormatString(@"手动速度 = %d", onTime.manualSpeed)];
    [strs addObject:FormatString(@"自动速度 = %d", onTime.autoSpeed)];
    [strs addObject:FormatString(@"动作警报 = %d", onTime.moveWarning)];
    [strs addObject:FormatString(@"系统警报 = %d", onTime.sysWarning)];
    
    for (int i=0; i<8; i++) {
        unsigned char warning = onTime.warning[i];
        [strs addObject:FormatString(@"轴%d伺服警报 = %d", i+1, warning)];
    }
    [strs addObject:FormatString(@"BlockNo = %d", onTime.blockNo)];
    [strs addObject:FormatString(@"BlockComment = %@", DataToString(onTime.blockComment))];
    
    [self showText:FormatString(@"通信数据:\n%@",[strs componentsJoinedByString:@"\n"])];
}


#pragma mark -  发送数据
- (void)actionButtonClick:(NSMButton *)sender{
    struct BSHeaderSend header;
    memset(&header, 0, sizeof(header));
    header.seq = '2';
    header.cmd = 'O';
    header.len = htons(12);
    
    struct BSDataSendO  send;
    memset(&send, 0, sizeof(send));
    send.header = header;

    // 原来smo2个字节 右移8位得到第一个字节
    unsigned char flag = self.recvO.smo >> 8;
    unsigned char operate = 0;
    // 前4个字节中只能有1个是0
    switch (sender.tag) {
        case 0:
        {
            // 1 手动 00000001
            SetBit(flag, 0);
            ClearBit(flag, 1);
            ClearBit(flag, 2);
            ClearBit(flag, 3);
        }
            break;
        case 1:
        {
            // 2 原点复位 00000010
            int tempFlag = 0;
            SetBit(tempFlag, 1);
            SetBit(tempFlag, 4);
            int tempOperate = 0;
            SetBit(tempOperate, 0);
            flag = tempFlag;
            operate = tempOperate;
        }
            break;
        case 2:
        {
            // 4 步进 00000100
            SetBit(flag, 2);
            ClearBit(flag, 0);
            ClearBit(flag, 2);
            ClearBit(flag, 3);
        }
            break;
        case 3:
        {
            // 8 自动 00001000
            SetBit(flag, 3);
            ClearBit(flag, 0);
            ClearBit(flag, 1);
            ClearBit(flag, 2);
        }
            break;
        case 4:
        {
            // 手动速度+
            // 标志位 00000001
            unsigned char bit = 0;
            send.flg = 1;
            // 操作位 00001000
            SetBit(bit, 3);
            send.operate = bit;
            // 手动速度
            send.manualSpeed = MIN(5, self.recvO.manualSpeed+1);
            // 自动速度(带上)
            send.autoSpeed = self.recvO.autoSpeed;
        }
            break;
        case 5:
        {
            // 手动速度-
            // 标志位 00000001
            unsigned char bit = 0;
            send.flg = 1;
            // 操作位 00001000
            SetBit(bit, 3);
            send.operate = bit;
            // 手动速度
            send.manualSpeed = MAX(1, self.recvO.manualSpeed-1);
            // 自动速度(带上)
            send.autoSpeed = self.recvO.autoSpeed;
        }
            break;
        case 6:
        {
            // 自动速度+
            // 标志位 00001000
            unsigned char flagBit = 0;
            SetBit(flagBit, 3);
            send.flg = flagBit;
            // 操作位 00001000
            unsigned char operateBit = 0;
            SetBit(operateBit, 3);
            send.operate = operateBit;
            // 自动速度
            send.autoSpeed = MIN(5, self.recvO.autoSpeed+1);
            // 手动速度(带上)
            send.manualSpeed = self.recvO.manualSpeed;

        }
            break;
        case 7:
        {
            // 自动速度-
            // 标志位 00001000
            unsigned char flagBit = 0;
            SetBit(flagBit, 3);
            send.flg = flagBit;
            // 操作位 00001000
            unsigned char operateBit = 0;
            SetBit(operateBit, 3);
            send.operate = operateBit;
            // 自动速度
            send.autoSpeed = MAX(1, self.recvO.autoSpeed-1);
            // 手动速度(带上)
            send.manualSpeed = self.recvO.manualSpeed;
        }
            break;
        case 8:
        {
            // 自动开始
            // 标志位 00011000
            unsigned char flagBit = 0;
            SetBit(flagBit, 3);
            SetBit(flagBit, 4);
            send.flg = flagBit;
        }
            break;
        case 9:
        {
          // 自动暂停
            // 标志位 00101000
            unsigned char flagBit = 0;
            SetBit(flagBit, 3);
            SetBit(flagBit, 5);
            send.flg = flagBit;
            
            
        }
            break;
            
        default:
            break;
    }
    send.flg = flag;
    send.operate = operate;
    send.dpCode = 1;
    NSData *data = [NSData dataWithBytes:&send length:sizeof(send)];
    [_bsSocket send:data];
}

- (void)sendW {
    [self wCmd:NO];
}

- (void)wCmd:(BOOL)close {
    struct BSHeaderSend header;
    memset(&header, 0, sizeof(header));
    header.seq = '2';
    header.cmd = 'W';
    header.len = htons(1);
    
    struct BSWInfo winfo;
    memset(&winfo, 0, sizeof(winfo));
    winfo.header = header;
    winfo.value = close?0:1;
    
    NSData *data = [NSData dataWithBytes:&winfo length:sizeof(winfo)];
    [_bsSocket send:data];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (close) {
            [_bsSocket close];
        }
    });
}

@end
